#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdio.h>
#include <syslog.h>
#include <signal.h>
#include <string.h>
#include <strings.h>
#include <errno.h>

#define MAXLONG 80 /*Maximo tamanho de un string*/
#define TCP_PORT 1138

int main() {

	int sock, fd, cliente_long;
	struct sockaddr_in server, client;
	char hostname[MAXLONG];
	
	if((sock=socket(AF_INET,SOCK_STREAM,0))<0) {
		fprintf(stderr,"S: Error creando stream socket\n");
		return -1;
	}
	
	server.sin_family = AF_INET;
	server.sin_addr.s_addr = htonl(INADDR_ANY);
	server.sin_port = htons(TCP_PORT);
	
	if (bind(sock,(struct sockaddr *)&server,sizeof(server))<0) {
		fprintf(stderr,"S: Error binding socket");
		return -1;
	}
	
	if(listen(sock,5)<0) {
		fprintf(stderr,"S: Error listen\n");
		return -1;
	}

	gethostname(hostname,MAXLONG);
	
	while (1) {
		fprintf(stdout,"S: Servidor en %s:%d esperando cliente!\n",hostname,TCP_PORT);
		cliente_long=sizeof(client);
		if((fd=accept(sock,(struct sockaddr *)&client,&cliente_long))<0) {
			fprintf(stderr,"S: Error aceptando la conexion\n");
			return -1;
		}
		conversar_cliente(fd,fd);
		close(fd);
	}
	fprintf(stderr,"S: No se por que, pero me cierro\n");

	return 0;
}

/*Espera a que el cliente escriba algo, contesta el mensaje recibido
Bucle hasta que el cliente cierre la conexion*/
int conversar_cliente(int in, int out) {	
	char buf[MAXLONG];
	int leido;

	fprintf(stdout,"S: Conversando!\n");
	/*Lee un intervalo*/
	leido=1;
	do {	
		memset (buf,'\0',MAXLONG);
		leido=read(in,buf,MAXLONG);
		if(leido<0) {
			fprintf(stdout,"S: Error :(\n");
		} else if (leido==0) {
			fprintf(stdout,"S: Cliente se ha ido :(\n");
		} else {
			fprintf(stdout,"C: %s\n",buf);
			write(out,buf,strlen(buf));
		}
	}while(leido);

	return leido;
}
